package com.raycloud.dingtalk.starter.demo;

import cn.hutool.json.JSONUtil;
import com.raycloud.dingtalk.starter.context.CommandContext;
import com.raycloud.dingtalk.starter.model.DingTalkReq;
import com.raycloud.dingtalk.starter.model.DingTalkResp;
import com.raycloud.dingtalk.starter.prop.DingTalkProp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/dingtalk")
@Slf4j
public class DingtalkController {

    @Autowired
    private DingTalkProp prop;

    @Autowired
    private HttpServletRequest request;

    private static final CommandLineParser parser = new DefaultParser();


    @RequestMapping("/commond")
    public  String process(@RequestBody DingTalkReq dingTalkReq) {

        log.info("cmd: {}", JSONUtil.toJsonStr(dingTalkReq));
        if (!prop.getDingToken().equals(request.getHeader("token"))) {
            throw new IllegalArgumentException("非法调用");
        }
        String[] args = dingTalkReq.getText().getContent().trim().split(" ");
        String command = args[0];
        DingTalkResp resp = new DingTalkResp();
        String resultText;
        try {
            if (!CommandContext.support(command)) {
                resultText = String.format(">_< 不要欺负我了\n%s", CommandContext.buildCommandHelp());
            } else {
                CommandLine cmd = parser.parse(CommandContext.buildOptions(command), args);
                resultText = CommandContext.of(command).handle(cmd.getOptions());
            }
        } catch (Exception e) {
            log.error("error", e);
            if (e instanceof ParseException) {
                resultText = String.format("哦？是吗？如需帮助可使用: %s -h", command);
            } else {
                resultText = String.format("执行出错: %s", e.getMessage());
            }
        }
        resp.setText(new DingTalkReq.DingTalkText(resultText));
        resp.setAt(new DingTalkResp.DingTalkAt().addDingTalkAd(dingTalkReq.getSenderId()));
        return JSONUtil.toJsonStr(resp);
    }
}
